<template>
  <div class="distribution-wrap">
    <el-dialog :visible.sync="dialogVisible.show" center>
      <div class="show-name">分组ID：{{ org_id_check }}</div>
      <div class="show-nick">分组名称：{{ org_name }}</div>
      <div class="tree-wrap">
        <el-input
          placeholder="输入关键字"
          style="margin-top: 10px;"
          prefix-icon="el-icon-search"
          clearable
          @input="fnSearch"
          v-model="filterText"
        ></el-input>
        <el-button
          class="submit-btn"
          type="primary"
          size="small"
          @click="fnSubmit"
          :loading="submitLoading"
          :disabled="submitDisable"
        >
          提交
          <i class="el-icon-upload2 el-icon--right"></i>
        </el-button>
        <div class="scroll-box">
          <div class="wrap">
            <el-tree
              ref="tree"
              class="filter-tree"
              :data="datas"
              :props="defaultProps"
              node-key="sn"
              :default-expanded-keys="[1]"
              :default-checked-keys="defaultCheckData"
              :accordion="true"
              @node-click="handleNodeClick"
              show-checkbox
              :checked="checked"
              @check="currentChecked"
              v-if="treeLoading"
            >
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <div
                  :class="{
                    red: data.online == 0,
                    green: data.online == 1,
                    gray: data.online == -1,
                  }"
                ></div>
                <span :title="data.label">{{ data.label }}</span>
              </span>
            </el-tree>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getData, postData } from "@/request/http";
export default {
  name: "audit",
  props: {
    org_id_check: {
      type: String,
      default: "",
    },
    org_name: {
      type: String,
      default: "",
    },
    dialogVisible: {
      type: Object,
      default() {
        return {
          show: false,
        };
      },
    },
  },
  data() {
    return {
      schedule_id: "",
      desc: "",
      filterText: "",
      data: [
        {
          id: 1,
          label: "部门1",
          children: [
            {
              id: 4,
              label: "摄像机1-内蒙",
            },
            {
              id: 11,
              label: "摄像机1-内蒙",
            },
          ],
        },
      ],
      defaultProps: {
        children: "children",
        label: "label",
      },
      datas: [],

      resData: [],
      serchResult: [],
      arrResult: [],
      checked: [1], // 默认选中数据
      checkedKeys: [], // 选中的key
      submit_arr: [],
      defaultCheckData: [],
      treeLoading: false,
      checkedArr: [],
      submitDisable: false,
      submitLoading: false,
    };
  },
  watch: {},
  mounted() {
    this.getList();
    this.checkedKeys = [];
  },
  methods: {
    /*
     *@Des: 获取初始列表
     *@Author: hhh, 2021-12-24 14:15:56
     */
    getList() {
      this.datas = [];
      postData(
        "/adminweb/admin/device/list/byorgtree/ext",
        {
          bind_for: "ORG",
          bind_for_id: this.org_id_check,
          with_online: 1,
          with_only_noorg: 1,
        },
        {
          timeout: 120000,
        }
      )
        .then((res) => {
          this.treeLoading = false;
          if (res.code == 0) {
            this.defaultCheckData = [];
            this.checkedArr = [];
            let data = res.datas.gfathers;
            if (!data) {
              return;
            } else {
              console.log(data);
              console.log(this.datas);
              //初始的时候，根据authorized，勾选上
              // for (var i = 0; i < data.length; i++) {
              //   var datas = data[i].children;
              //   for (var j = 0; j < datas.length; j++) {
              //     if (datas[j].authorized == 1) {
              //       this.datas.push(data[j].sn);
              //     }
              //   }
              // }
              this.getData(data, this.datas, 0);
              this.serchResult = JSON.parse(JSON.stringify(this.datas));
            }
          } else if (res.code == -56055) {
            return;
          } else {
            this.$message.error(res.code + "，" + res.msg);
          }
          this.treeLoading = true;
          console.log(this.defaultCheckData);
        })
        .catch((res) => {
          this.$message.error("error");
        });
    },
    /*
     *@Des:  搜索
     *@Author: hhh, 2021-12-24 14:15:35
     */
    fnSearch(val) {
      this.arrResult = [];
      this.filterResult(val, this.serchResult);
      this.datas = this.arrResult;
      if (val.trim().length == 0) {
        this.datas = this.serchResult;
      }
    },
    /*
     *@Des:  计算数组,搜索
     *@Author: hhh, 2021-12-24 14:15:45
     */
    filterResult(val, arr) {
      if (Array.isArray(arr) && arr.length > 0 && !!val.trim()) {
        for (let i = 0; i < arr.length; i++) {
          let item = arr[i];
          if (item.label && item.label.search(val.toString()) != -1) {
            this.arrResult.push(item);
          }
          if (item.children) {
            this.filterResult(val, item.children);
          }
        }
      }
    },
    /*
      递归设置children  根据recording_channels数组来设置通道节点
    */
    getData(data, arr, index) {
      index++;
      if (Array.isArray(data) && data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          let item = data[i];
          console.log(item);
          let obj = {};
          obj["id"] = Math.floor(Math.random() * 10000000).toString();
          obj["sn"] = !item["sn"] ? item["org_id"] : item["sn"];
          obj["label"] =
            item.gfather_name ||
            item.father_name ||
            item.org_name ||
            item.alias;
          obj["reg_type"] = item["reg_type"];
          obj["index"] = index;
          obj["online"] = item["online"];
          obj["authorized"] = item["authorized"];
          obj["recording_channels"] = !item["recording_channels"]
            ? []
            : item["recording_channels"];
          //没有chns
          obj["children"] = [];
          if (item["authorized"] == 1) {
            this.defaultCheckData.push(obj["sn"]);
          }
          //有chns
          /*   if (!!item["chns"] && item["chns"] > 1) {
            let result = [];
            for (let h = 1; h <= item["chns"]; h++) {
              result.push({
                label: "通道 " + h,
                children: [],
                onlineType: item["online"],
                reg_type: item["reg_type"],
                index: 4,
                id: Math.floor(Math.random() * 10000000).toString(),
                sn: !item["sn"] ? item["org_id"] : item["sn"],
                chns: h - 1,
                parent_label: obj["label"],
              });
            }
            obj["children"] = result;
          } */

          /*   if (!!item["recording_channels"]) {
            if (
              Array.isArray(item["recording_channels"]) &&
              item["recording_channels"].length > 0 &&
              Array.isArray(obj["children"]) &&
              obj["children"].length > 0
            ) {
              for (let j = 0; j < item["recording_channels"].length; j++) {
                this.defaultCheckData.push(
                  obj["children"][item["recording_channels"][j]]["id"]
                );
                let objs = {};
                objs.sn = obj["children"][item["recording_channels"][j]].sn;
                objs.channel =
                  obj["children"][item["recording_channels"][j]].chns;
                this.checkedArr.push(objs);
              }
            } else if (
              Array.isArray(item["recording_channels"]) &&
              item["recording_channels"].length > 0 &&
              !item["children"]
            ) {
              //console.log(item["children"], item["recording_channels"]);
              this.defaultCheckData.push(obj["id"]);
              let objs = {};
              objs.sn = obj.sn;
              objs.channel = item.chns;
              this.checkedArr.push(objs);
            }
          } */

          arr.push(obj);
          //console.log(arr);

          if (item["fathers"] && !item["chns"]) {
            this.getData(item["fathers"], obj["children"], index);
          } else if (item["orgs"] && !item["chns"]) {
            this.getData(item["orgs"], obj["children"], index);
          } else if (item["devices"] && !item["chns"]) {
            this.getData(item["devices"], obj["children"], index);
          }
        }
      }
    },
    //currentChecked
    currentChecked(data, node) {},

    // 设置数据
    setCheckData() {
      let checkData = this.$refs.tree.getCheckedNodes(true);
      console.log(checkData);
      if (Array.isArray(checkData) && checkData.length > 0) {
        for (let i = 0; i < checkData.length; i++) {
          let item = checkData[i];
          this.submit_arr.push(item.sn);
          //   if (typeof item.chns != "undefined") {
          //     let obj = {};
          //     obj.sn = item.sn;
          //     obj.channel = item.chns;
          //     this.submit_arr.push(obj);
          //   } else {
          //     let obj = {};
          //     obj.sn = item.sn;
          //     this.submit_arr.push(obj);
          //   }
        }
        console.log(this.submit_arr);
      }
    },

    //提交
    fnSubmit() {
      this.submitDisable = true;
      this.submitLoading = true;
      this.setCheckData(); // 设置数据
      var that = this;
      postData(
        "/adminweb/org/device/set",
        {
          org_id: that.org_id_check,
          devices: that.submit_arr,
        },
        {
          timeout: 120000,
        }
      )
        .then((res) => {
          that.submitDisable = false;
          that.submitLoading = false;
          if (res.code == 0) {
            that.$message.success("提交成功！");
            that.$emit("refreshTableList");
            that.getList();
          } else {
            that.$message.error(res.code + "，" + res.msg);
          }
        })
        .catch((res) => {
          that.submitDisable = false;
          that.submitLoading = false;
          that.$message.error(res.code + "，" + res.msg);
        });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    //click tree
    async handleNodeClick(data) {},
  },
};
</script>

<style scoped>
.distribution-wrap >>> .el-dialog {
  width: 60%;
}
.center {
  width: 100%;
  height: 530px;
  margin-top: 15px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}
.show-name {
  height: 30px;
  line-height: 30px;
  font-weight: 600;
  color: #676a6d;
  font-size: 15px;
  display: inline-block;
}
.show-nick {
  margin-left: 50px;
  height: 30px;
  line-height: 30px;
  font-weight: 600;
  color: #676a6d;
  font-size: 15px;
  display: inline-block;
}
.tree-wrap {
  width: 100%;
  height: 100%;
  display: flex;
  flex-flow: column;
  justify-content: flex-start;
  overflow: hidden;
}
.submit-btn {
  display: block;
  width: 68px;
  margin-top: 10px;
}
.wrap {
  width: 100%;
  height: auto;
  overflow-y: hidden;
}
.scroll-box {
  width: 100%;
  height: calc(100% - 100px);
  overflow-x: hidden;
  overflow-y: auto;
}

.tree-wrap >>> .el-tree {
  margin-top: 20px;
  background: #fff;
}
.tree-wrap >>> .el-input__inner {
  background: #fff;
  border: 1px solid #4676d4;
  height: 35px;
  line-height: 35px;
}

.tree-wrap >>> .happy-scroll-container {
  width: 100% !important;
  display: flex;
  flex-flow: column;
}

.tree-wrap >>> .el-tree-node {
  position: relative;
}
.tree-wrap >>> .custom-tree-node {
  font-size: 14px;
  padding-right: 8px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.red {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: #f13636;
  margin-right: 10px;
}
.green {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: rgb(38 179 38);
  margin-right: 10px;
}
.gray {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: #838486;
  margin-right: 10px;
}
</style>
